#include <jni.h>
#include <string>
#include "quickjs.h"
#include "quickjs-libc.h"

extern "C" JNIEXPORT jstring JNICALL Java_com_example_qjssoandroid_MainActivity_initializeQuickJS(JNIEnv *env, jobject,
                                                                 jstring jsCode) {

    const char *code = env->GetStringUTFChars(jsCode, nullptr);

    JSRuntime *runtime = JS_NewRuntime();
    JSContext *ctx = JS_NewContext(runtime);

    JSValue result = JS_Eval(ctx, code, strlen(code), "<input>", JS_EVAL_TYPE_GLOBAL);

    const char *result_str = JS_ToCString(ctx, result);
    jstring output = env->NewStringUTF(result_str);

    JS_FreeCString(ctx, result_str);
    JS_FreeValue(ctx, result);
    JS_FreeContext(ctx);
    JS_FreeRuntime(runtime);

    env->ReleaseStringUTFChars(jsCode, code);

    return output;
}
